package dao.oracle;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.PooledConnection;

import oracle.jdbc.pool.OracleConnectionPoolDataSource;

/**
 * Provide to connect with the Oracle DB
 * @author Ilya_Poliakov
 */
public class OracleConnection {

	//TODO: make a non-static OracleConnection. OracleConnection realize as object and use in daoFactory. Use singleton.
	private static Connection connection = null;
	private static final String INITIAL_LIMIT_PROPERTY_NAME = "InitialLimit";
	private static final String INITIAL_LIMIT_PROPERTY_VALUE = "1";
	private static final String IS_CONNECTED = "Oracle DB successfully connected";
	private static final String IS_NOT_CONNECTED = "Oracle DB connection failed";
	private static final String MAX_LIMIT_PROPERTY_NAME = "MaxLimit";
	private static final String MAX_LIMIT_PROPERTY_VALUE = "100";
	private static final String MIN_LIMIT_PROPERTY_NAME = "MinLimit";
	private static final String MIN_LIMIT_PROPERTY_VALUE = "1";
	private static final String PASSWORD = "marketplace";
	private static PooledConnection pooledConnection = null;
	private static final String PORT = "1521";
	private static final String SERVER = "localhost";
	private static final String SID = "XE";
	private static final String URL = "jdbc:oracle:thin:@%s:%s:%s";
	private static final String USERNAME = "marketplace_usr";


	/**
	 * close the pooled connection
	 */
	public void close() {
		try {
			pooledConnection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Create new pooled connection
	 */
	private void createPooledConnection() {
		try {
			OracleConnectionPoolDataSource src = new OracleConnectionPoolDataSource();
			String url = String.format(URL, SERVER, PORT, SID);
			src.setURL(url);
			src.setUser(USERNAME);
			src.setPassword(PASSWORD);
			Properties cacheProps = new Properties();
			cacheProps.setProperty(MIN_LIMIT_PROPERTY_NAME,
					MIN_LIMIT_PROPERTY_VALUE);
			cacheProps.setProperty(MAX_LIMIT_PROPERTY_NAME,
					MAX_LIMIT_PROPERTY_VALUE);
			cacheProps.setProperty(INITIAL_LIMIT_PROPERTY_NAME,
					INITIAL_LIMIT_PROPERTY_VALUE);
			src.setConnectionCacheProperties(cacheProps);
			pooledConnection = src.getPooledConnection();
			if (pooledConnection != null)
				System.out.println(IS_CONNECTED);
		} catch (SQLException e) {
			System.out.println(IS_NOT_CONNECTED);
			e.printStackTrace();
		}
	}

	/**
	 * Return the Oracle connection
	 * @return the connection
	 */
	public Connection getConnection() {
		if (pooledConnection == null) {
			createPooledConnection();
		}
		try {
			connection = pooledConnection.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

}